package com.ww.yaodao.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ww.yaodao.mapper.RegisterMapper;
import com.ww.yaodao.model.bo.UserDO;
import com.ww.yaodao.service.RegisterService;
import com.ww.yaodao.util.HttpUtils;
import com.ww.yaodao.util.PasswordUtils;
import com.ww.yaodao.model.vo.RegisterVO;
import com.ww.yaodao.util.md5Utils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private RegisterMapper registerMapper;

    @Override
    public int addOneUser(RegisterVO registerVO) {
        /*
         * 重要提示如下:
         * HttpUtils请从
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
         * 下载
         *
         * 相应的依赖请参照
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
         */
        String host = "https://idenauthen.market.alicloudapi.com";
        String path = "/idenAuthentication";
        String method = "POST";
        String appcode = "73cc99016e0244f292cc7d95996080ad";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idNo", registerVO.getIdentifyCard());
        bodys.put("name", registerVO.getUsername());
        try {
            HttpResponse response =
                    HttpUtils.doPost(host, path, method, headers, querys, bodys);
            if (response.getEntity() != null) {
                // 使用md5对密码、身份证进行加密
                registerVO.setPassword(PasswordUtils.generate(registerVO.getPassword()));
                registerVO.setIdentifyCard(PasswordUtils.generate(registerVO.getIdentifyCard()));
                // 糊涂工具类进行拷贝
                UserDO userDO = BeanUtil.copyProperties(registerVO, UserDO.class);
                userDO.setUtype(1);
                userDO.setAid(1);
                userDO.setPassword(registerVO.getPassword());
                int insert = registerMapper.insert(userDO);
                return insert;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }
}
